package com.mengchengnet.chaperonage.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.domain.base.Service;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/10/23.
 */

public class AddService extends BaseActivity implements View.OnClickListener{
    private TextView tv_save,type,sort,unit,add,showTime;
    private ImageView iv_select;
    private EditText content,price;
    private RequestQueue requestQueue;
    List<Service> list =new ArrayList<Service>();
    private String cateId;//陪护分类id，用户区分陪护种类
    private String userId;
    private String serviceId;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
             if (!list.get(0).getUnit().isEmpty()){
                 unit.setText(list.get(0).getUnit());
                 //serviceId=list.get(0).getId();
             }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_service);
        toolbarState=TOOLBAR_SHOW_TEXT;
        initToolbar("添加服务类型");
        ininView();
    }

    private void ininView() {
        requestQueue= Volley.newRequestQueue(getApplication());
        cateId=PreferenceUtil.getString(getApplication(),"cate_id");
        userId= PreferenceUtil.getString(this,"userId");
        tv_save= (TextView) findViewById(R.id.tvToolbarPosition);
        tv_save.setText("保存");
        tv_save.setOnClickListener(this);
        type= (TextView) findViewById(R.id.add_service_type);
        sort= (TextView) findViewById(R.id.add_service_sort);
        unit= (TextView) findViewById(R.id.add_service_price);
        add= (TextView) findViewById(R.id.add_service_add);
        add.setOnClickListener(this);
        content= (EditText) findViewById(R.id.add_service_content);
        iv_select= (ImageView) findViewById(R.id.add_service_go);
        iv_select.setOnClickListener(this);
        price= (EditText) findViewById(R.id.add_service_ed_price);
        showTime= (TextView) findViewById(R.id.add_service_showTime);
        if (cateId.equals("1")){
            type.setText("护工");
        }else if(cateId.equals(2)){
            type.setText("月嫂");
        }else if(cateId.equals(3)){
            type.setText("育婴师");
        }else if(cateId.equals(4)){
            type.setText("催乳师");
        }
        list.clear();
        getService();
    }

    private void getService(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.getService,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("getService", "返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                JSONArray array=jsonObject.getJSONArray("careList");
                                for (int i = 0; i <array.length() ; i++) {
                                    JSONObject obj=array.getJSONObject(i);
                                    String name=obj.getString("name");
                                    String id=obj.getString("id");
                                    String content=obj.getString("content");
                                    String unit=obj.getString("unit");

                                    Service s=new Service();
                                    s.setId(id);
                                    s.setName(name);
                                    s.setContent(content);
                                    s.setUnit(unit);
                                    list.add(s);


                                }
                                handler.sendEmptyMessage(0);

                            }
                            else {
                                Toast.makeText(AddService.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(AddService.this, "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("cateId", cateId);
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    private void saveService(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.saveService,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("getService", "返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                Toast.makeText(AddService.this, "添加成功", Toast.LENGTH_SHORT).show();

                            }
                            else {
                                Toast.makeText(AddService.this, "添加失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(AddService.this, "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("loginId", userId);//陪护id
                map.put("cate_id", cateId);//分类id
                map.put("sid", serviceId);//服务id
                map.put("stime", cateId);//服务时间
                map.put("price", price.getText().toString());
                map.put("content", content.getText().toString());
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    private void showDialog(){
        final String [] item=new String[list.size()];
        final String [] item2=new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            item[i]=list.get(i).getName();
            item2[i]=list.get(i).getId();
        }
        new AlertDialog.Builder(this).setTitle("服务类型").setItems(item, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(AddService.this, item[which], Toast.LENGTH_SHORT).show();
                sort.setText(item[which]);
                serviceId=item2[which];
            }
        }).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.add_service_go:
                showDialog();
                break;
            case R.id.tvToolbarPosition:
                if (sort.getText().toString().isEmpty()){
                    Toast.makeText(this, "请设置服务方式", Toast.LENGTH_SHORT).show();
                }else if(price.getText().toString().isEmpty()){
                    Toast.makeText(this, "请设置服务价格", Toast.LENGTH_SHORT).show();
                }else{
                    saveService();
                }

                break;
            case R.id.add_service_add:
                Intent intent=new Intent(AddService.this,CalanderActivity.class);
                intent.putExtra("mode","0");
                //startActivity(intent);
                startActivityForResult(intent,1);
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if (resultCode==RESULT_OK){
                    String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
                    if (!result.isEmpty()){
                        showTime.setText(result);
                    }


                }
                break;
        }
    }
}
